import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from 'element-plus';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            redirect: "/cloud"
        },
        {
            path: '/404',
            component: () => import("@/views/404.vue"),
            name: '404'
        },
        {
            path: '/:pathMatch(.*)',
            redirect: '/404',
        },
        {
            path: "/login",
            component: () => import("@/views/login/login.vue")
        },
        {
            path: "/cloud",
            component: () => import("@/views/cloud/index.vue"),
            name: "cloud-index"
        },
        {
            path: "/cloud/upload",
            component: () => import("@/views/cloud/upload.vue"),
            name: "cloud-upload"
        },
        {
            path: "/cloud/download",
            component: () => import("@/views/cloud/download.vue"),
            name: "cloud-download"
        },
        {
            path: "/cloud/manage",
            component: () => import("@/views/cloud/manage.vue"),
            name: "cloud-manage"
        },
        {
            path: "/admin",
            component: () => import("@/views/admin/layout.vue"),
            redirect: "/admin/dashboard",
            children: [
                {
                    path: "dashboard",
                    component: () => import("@/views/admin/dashboard.vue"),
                    name: "admin-dashboard"
                },
                {
                    path: "users",
                    component: () => import("@/views/admin/users.vue"),
                    name: "admin-users"
                },
                {
                    path: "files",
                    component: () => import("@/views/admin/files.vue"),
                    name: "admin-files"
                }
            ]
        }
    ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');
    const publicPages = ['/cloud', '/login'];
    const isPublicPage = publicPages.includes(to.path);


    // 如果是公开页面，允许访问
    if (isPublicPage) {
        next();
        return;
    }

    if (!token) {
        // 如果没有 token，重定向到登录页面
        next('/login');
        return;
    }

    next();
});

export default router;
